﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace DBService
{
	public partial class DlgRegistrate : System.Windows.Forms.Form
	{
		public DlgRegistrate(string group)
		{
			this.mGroup = group;
			this.InitializeComponent();
		}

		private void DlgAddUser_Load(object sender, EventArgs e)
		{
		}

		private void label4_Click(object sender, EventArgs e)
		{
		}

		private void textBox3_TextChanged(object sender, EventArgs e)
		{
		}

		private void btnOK_Click(object sender, EventArgs e)
		{
			try
			{
				if (this.txtName.Text.Trim() == "" || this.txtPassword.Text.Trim() == "")
				{
					MessageBox.Show("请填写用户名和密码。");
				}
				else if (!this.txtPassword.Text.Trim().Equals(this.txtPass.Text.Trim()))
				{
					this.txtPassword.Text = "";
					this.txtPass.Text = "";
					MessageBox.Show("两次输入密码不一致，请重新输入。");
				}
				else if (!this.IsValidEmail(this.txtEmail.Text))
				{
					this.txtEmail.Text = "";
					MessageBox.Show("邮箱格式不正确，请重新输入。");
				}
				else
				{
					using (List<DbUser>.Enumerator enumerator = DbUser.GetAllUsers(BimServerDB.Default).GetEnumerator())
					{
						while (enumerator.MoveNext())
						{
							if (enumerator.Current.Name == this.txtName.Text.Trim())
							{
								MessageBox.Show("该用户名已存在。");
								this.txtName.Focus();
								return;
							}
						}
					}
					DbUser dbUser = new DbUser(this.txtName.Text.Trim(), this.txtEmail.Text.Trim(), DbUser.ToMd5(this.txtPassword.Text.Trim()), this.txtChineseName.Text.Trim());
					dbUser.AddToDb(BimServerDB.Default);
					DbUser.System.SendMessage("admin", "新用户（" + dbUser.Name + "）提交注册，请审核。");
					MessageBox.Show("注册成功！");
					base.Close();
				}
			}
			catch (Exception)
			{
				this.txtName.Text = "";
				MessageBox.Show("注册失败，该用户名已存在！");
			}
		}

		private bool IsValidEmail(string strEmail)
		{
			return Regex.IsMatch(strEmail, "^[\\w\\.]+([-]\\w+)*@[A-Za-z0-9-_]+[\\.][A-Za-z0-9-_]");
		}

		private void btnCancle_Click(object sender, EventArgs e)
		{
			base.Close();
		}

		private string mGroup = "";
	}
}
